import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/login/index.vue'
import Layout from '@/layout/index.vue'
import ConstantType from '@/views/constantType/index.vue'
import ConstantItem from '@/views/constantItem/index.vue'
import User from '@/views/user/index.vue'
import Registration from '@/views/registration/index.vue'
import Doctor from '@/views/doctor/index.vue'
import Charge from '@/views/charge/index.vue'
import Check from '@/views/check/index.vue'
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/login' // 将根路径重定向到登录页
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/layout',
      name: 'Layout',
      component: Layout,
      children:[{
        path: '/constantType',
        name: 'ConstantType',
        component: ConstantType
      },
      {
        path: '/constantItem',
        name: 'ConstantItem',
        component: ConstantItem
      },
      {
        path: '/user',
        name: 'User',
        component: User
      },
      {
        path: '/registration',
        name: 'Registration',
        component: Registration
      },
      {
        path: '/doctor',
        name: 'Doctor',
        component: Doctor
      },
      {
        path: '/charge',
        name: 'Charge',
        component: Charge
      },
      {
        path: '/check',
        name: 'Check',
        component: Check
      }
    ]
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 如果访问根路径，重定向到登录页
  if (to.path === '/') {
    return next('/login')
  }
  
  // 检查需要认证的路由
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 这里添加你的认证逻辑，例如检查token
    const isAuthenticated = checkAuth() // 假设有一个检查认证的函数
    if (!isAuthenticated) {
      return next('/login') // 未认证则跳转到登录页
    }
  }
  
  next() // 其他情况正常放行
})

// 模拟认证检查函数
function checkAuth() {
  // 实际项目中这里应该检查本地存储的token等
  return localStorage.getItem('token') !== null
}

export default router
